<script setup>
import { ref, onMounted } from 'vue';
import { listUser ,addProject} from '@/api/project.js';
import {getStudentInfo,getTeacherInfo,} from '@/api/student.js';
import {uploadAddProjectFile,deleteProjectFile,exportProject} from '@/api/project.js'
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import {ElAvatar, ElMessage, ElMessageBox} from 'element-plus';
import routes from '@/router/index.js'
import {Plus} from "@element-plus/icons-vue";
const  student_display = ref(false)
const  teacher_display = ref(false)
const  addProject_display = ref(false)
const  student_data = ref([]);
const  teacher_data = ref([]);
const  student_total = ref(0)
const  teacher_total = ref(0)
const  selete_student = ref(null)
const  selete_teacher = ref(null)

// 配置富文本编辑器的工具栏选项
const editorOptions = {
  placeholder: '请输入内容',
  theme: "snow", // 设置编辑器的主题
  modules: {
    toolbar: [
      [{ 'header': '1' }, { 'header': '2' }, { 'font': [] }], // 字体大小、标题
      ['bold', 'italic', 'underline'], // 字体加粗、斜体、下划线
      [{ 'list': 'ordered' }, { 'list': 'bullet' }], // 列表
      [{ 'align': [] }], // 对齐方式
      [{ 'color': [] }, { 'background': [] }], // 字体颜色、背景颜色
      [{ 'size': ['small', 'medium', 'large', 'huge'] }], // 字体大小
      ['link', 'image'] // 插入链接和图片
    ]
  }
};

const filters = ref({
  userName: null,
  teacherName: null,
  projectName: null,
  type: null,
  pageNum: 1,
  pageSize: 9,
});
const filters_student = ref({
  userName:null,
  className:null,
  academy:null,

  pageNum:1,
  pageSize:5
})

const filters_teacher = ref({
  userName:null,
  professional:null,

  pageNum:1,
  pageSize:5
})
const AddProject =ref({
  userId: null,
  userName: null,
  teacherId: null,
  teacherName: null,
  projectName: null,
  description: null,
  startTime: null,
  endTime: null,
  image: null,
  lab: null,
  type: 1,
})

// 添加项目
const handleAddProject = async (AddProject) => {
  // 使用 ElMessageBox 确认
  ElMessageBox.confirm('您确定要添加这个项目吗?', '确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
      .then(async () => {
        // 用户点击确定后执行添加项目的逻辑
        const response = await addProject(AddProject);
        if (response.data.code === 200) {
          AddProject.value = response.data.data;
          ElMessage.success('申请成功，请等待审核通过');
          handleCancelAddProject();
          await fetchProjects();

        } else {
          ElMessage.error(response.data.msg || '添加失败');
        }
      })
      .catch(() => {
        // 用户点击取消的逻辑
        ElMessage.info('已取消添加项目');
      });
};
// 获取学生信息
const fetchStudents = async () => {
  student_display.value = true;
  console.log(student_display.value)
  const response = await getStudentInfo(filters_student.value);
  if (response.data.code === 200) {
    student_data.value = response.data.data.rows;
    console.log(student_data.value)
     student_total.value = response.data.data.total;
    console.log("总数" + total.value)
  } else {
    ElMessage.error(response.data.msg);
  }
}
// 获取教师信息
const fetchTeachers = async () => {
  teacher_display.value = true;
  const response = await getTeacherInfo(filters_teacher.value);
  if (response.data.code === 200) {
    teacher_data.value = response.data.data.rows;
    console.log(teacher_data.value)
    teacher_total.value = response.data.data.total;
    console.log("总数" + total.value)
  } else {
    ElMessage.error(response.data.msg);
  }
}

  const total = ref(0);
  const projects = ref([]);

// 类型映射
  const typeOptions = [
    {label: '人文社科', value: 1},
    {label: '理工科技', value: 2},
    {label: '艺术', value: 3},
  ];
  const goToDetailPage = (productId) => {
    routes.push({path: '/project-details', query: {productId}});
  };
// 查询数据
  const fetchProjects = async () => {
    try {
      const {data} = await listUser(filters.value);
      if (data.code === 200) {
        projects.value = data.data.rows;
        total.value = data.data.total;
      } else {
        ElMessage.error(data.msg || '查询失败');
      }
    } catch (error) {
      ElMessage.error('接口请求失败');
    }
  };

// 重置筛选条件
  const resetFilters = () => {
    filters.value = {
      userName: null,
      teacherName: null,
      projectName: null,
      type: null,
      pageNum: 1,
      pageSize: 9,
    };
    fetchProjects();
  };
// 重置筛选条件
const resetFilters_student = () => {
  filters_student.value = {
    userName:null,
    className:null,
    academy:null,
    pageNum:1,
    pageSize:5
  }
  fetchStudents();
}
// 重置筛选条件
const resetFilters_teacher = () => {
  filters_teacher.value = {
    userName:null,
    professional:null,
    pageNum:1,
    pageSize:5
  }
  fetchTeachers();
}


// 初始化加载
  onMounted(() => {
    fetchProjects();
  });

// 处理分页
  const handlePageChange = (page) => {
    filters.value.pageNum = page;
    fetchProjects();
  };


const handleStudentPageChange = (page) => {
  filters_student.value.pageNum = page;
   fetchStudents();
};
const handleTeacherPageChange = (page) => {
  filters_teacher.value.pageNum = page;
  fetchTeachers();
  };
// 上传图片
const uploadImage = async ({ file }) => {
  const formData = new FormData();
  formData.append('file', file);
  try {
    const response = await uploadAddProjectFile(formData);
    if (response.data.code === 200) {
      AddProject.value.image = response.data.data; // 假设后端返回图片 URL
      ElMessage.success('图片上传成功');
    } else {
      ElMessage.error(response.data.msg || '图片上传失败');
    }
  } catch (error) {
    ElMessage.error('接口请求失败');
  }
};

// 删除图片
const handleDeleteImage = async () => {
  try {
    const response = await deleteProjectFile(AddProject.value.image);
    if (response.data.code === 200) {
      AddProject.value.image = null;
      ElMessage.success('图片删除成功');
    } else {
      ElMessage.error(response.data.msg || '图片删除失败');
    }
  } catch (error) {
    ElMessage.error('接口请求失败');
  }
};
// 选择导师
const handleSelectTeacher = (teacher) => {
  if(AddProject.value.teacherId !==null){
    ElMessage.error('只能选择一个导师')
    return
  }
  AddProject.value.teacherId = teacher.id; // 假设教师对象有 id 和 name 字段
  AddProject.value.teacherName = teacher.name;
  selete_teacher.value = teacher;
  teacher_display.value = false; // 关闭弹窗
  ElMessage.success(`导师 ${teacher.name} 已添加`);
};

// 选择负责人
const handleSelectStudent = (student) => {
  if(AddProject.value.userId !==null){
    ElMessage.error('只能选择一个负责人')
    return
  }
  AddProject.value.userId = student.userId; // 假设学生对象有 id 和 name 字段
  AddProject.value.userName = student.userName;
  selete_student.value = student;
  student_display.value = false; // 关闭弹窗
  ElMessage.success(`负责人 ${student.userName} 已添加`);
};
//取消添加项目
const handleCancelAddProject = () => {
  addProject_display.value = false;
  uploadImage.value = null;
  AddProject.value = {
    userId: null,
    userName: null,
    teacherId: null,
    teacherName: null,
    projectName: null,
    description: null,
    startTime: null,
    endTime: null,
    image: null,
    lab: null,
  };
  selete_student.value = null;
  selete_teacher.value = null;
};

 //移除老师
const removeTeacher = (teacher) => {
  AddProject.value.teacherId = null;
  AddProject.value.teacherName = null;
  selete_teacher.value = null;
  ElMessage.success(`导师 ${teacher.name} 已移除`);
};
//移除学生
const removeStudent = (student) => {
  AddProject.value.userId = null;
  AddProject.value.userName = null;
  selete_student.value = null;
  ElMessage.success(`负责人 ${student.userName} 已移除`);
};
import { useUserStore } from '@/stores/user'
const userStore = useUserStore()
const user_name = userStore.userDetails.userName;

// 调用导出函数
const exportProjects = async () => {
  try {
    const response = await exportProject(user_name);
    // 创建 blob 对象
    const blob = new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
    const downloadUrl = window.URL.createObjectURL(blob);

    // 创建下载链接
    const link = document.createElement('a');
    link.href = downloadUrl;
    link.download = '项目信息.xlsx'; // 下载文件名
    document.body.appendChild(link);
    link.click();

    // 清理操作
    window.URL.revokeObjectURL(downloadUrl);
    document.body.removeChild(link);

    console.log("导出成功");
  } catch (error) {
    console.error("导出失败:", error);
  }
};



fetchProjects();
</script>

<template>

    <!-- 筛选条件 -->
    <el-form :model="filters" inline class="filter-form" >
      <el-form-item label="负责人">
        <el-input v-model="filters.userName" placeholder="请输入用户名" style="width: 130px;" />
      </el-form-item>
      <el-form-item label="指导老师">
        <el-input v-model="filters.teacherName" placeholder="请输入教师名" style="width: 130px;" />
      </el-form-item>
      <el-form-item label="项目名称">
        <el-input v-model="filters.projectName" placeholder="请输入项目名称" style="width: 130px;" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="fetchProjects">查询</el-button>
        <el-button @click="resetFilters">重置</el-button>
      </el-form-item>
<!--       添加项目按钮 -->
      <el-form-item v-if="userStore.userInfo === 'teacher'">
        <el-button type="success" @click="addProject_display=true">添加项目</el-button>
        <el-button type="success" @click="exportProjects">导出</el-button>
      </el-form-item>

    </el-form>
    <!-- 项目展示 -->
    <el-row :gutter="20" style="margin-left:-20px;width: 120%">
      <el-col :span="8" v-for="project in projects" :key="project.id">
        <el-card shadow="always" style="margin-top: 20px;height: 400px;">
          <img @click="goToDetailPage(project.id)" :src="project.image" alt="项目图片" style="width: 100%; height: 200px; object-fit: cover;" />
          <div style="margin-top: 10px;">
            <h3>{{ project.projectName }}</h3>
            <p>负责人：{{ project.userName }}</p>
            <p>指导教师：{{ project.teacherName }}</p>
            <p class="project-description" v-html="project.description"></p>

          </div>
        </el-card>
      </el-col>
    </el-row>



    <!-- 分页 -->
    <el-pagination
        background
        layout="total,  prev, pager, next"
        :current-page="filters.pageNum"
        :page-sizes="[9, 20, 30, 50]"
        :page-size="filters.pageSize"
        :total="total"
        @current-change="handlePageChange"
        @size-change="handleSizeChange"
        style="margin-top: 20px; margin-left: 150px;margin-bottom: 20px;"
    />


  <!-- 添加项目弹窗. -->
  <el-dialog v-model="addProject_display" title="添加项目" width="70%">

    <el-form :model="AddProject" label-width="80px">
      <el-form-item label="项目名称">
        <el-input v-model="AddProject.projectName" placeholder="请输入项目名称"></el-input>
      </el-form-item>
<!--      开始和结束时间-->
      <el-form-item label="开始时间">
        <el-date-picker v-model="AddProject.startTime" type="date" placeholder="选择日期"></el-date-picker>
      </el-form-item>
      <el-form-item label="结束时间">
        <el-date-picker v-model="AddProject.endTime" type="date" placeholder="选择日期"></el-date-picker>
      </el-form-item>
<!--      上传图片和删除图片-->
      <el-form-item label="项目图片">
        <el-upload
            action=""
            :http-request="uploadImage"
            list-type="picture-card"
            :show-file-list="false"
            accept="image/*"
        >
          <img v-if="AddProject.image" :src="AddProject.image" alt="项目图片" style="width: 100px; height: 100px;" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
        <el-button style="margin-left: 10px;" v-if="AddProject.image" type="danger" @click="handleDeleteImage">删除图片</el-button>
      </el-form-item>

<!--      实验室-->
      <el-form-item label="实验室">
        <el-input v-model="AddProject.lab" placeholder="请输入实验室"></el-input>
      </el-form-item>
<!--      富文本编辑器-->
      <el-form-item label="项目描述">
        <textarea  style="height: 300px; width: 100%;" v-model="AddProject.description" :options="editorOptions"></textarea>
      </el-form-item>
    </el-form>

    <div style="display:grid;">
      <h2>导师信息</h2>
      <el-table v-if="selete_teacher != null" :data="[selete_teacher]" style="">
<!--          头像-->
        <el-table-column label="头像" width="80">
          <template #default="{ row }">
            <el-avatar :size="40" :src="row.avatar || 'https://via.placeholder.com/80'"></el-avatar>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="姓名" width="140"></el-table-column>
        <el-table-column prop="major" label="研究方向" width="140"></el-table-column>
        <el-table-column prop="professional" label="职称" width="140"></el-table-column>
        <el-table-column prop="phone" label="电话" width="140"></el-table-column>
<!--        移除按钮-->
        <el-table-column label="操作" width="100">
          <template #default="{ row }">
            <el-button type="danger" @click="removeTeacher">移除</el-button>
          </template>
          </el-table-column>
      </el-table>

      <el-button v-if="selete_teacher == null" style="width: 100px; margin-left: 100px; margin-top: 20px;" type="primary" @click="fetchTeachers(); teacher_display = true">选择导师</el-button>

      <h2>负责人信息</h2>
      <el-table v-if="selete_student != null" :data="[selete_student]" style="">
        <el-table-column label="头像" width="80">
          <template #default="{ row }">
            <el-avatar :size="40" :src="row.avatar || 'https://via.placeholder.com/80'"></el-avatar>
          </template>
        </el-table-column>
        <el-table-column prop="userName" label="姓名" width="140"></el-table-column>
        <el-table-column prop="email" label="邮箱" width="140"></el-table-column>
        <el-table-column prop="phone" label="电话" width="140"></el-table-column>
        <el-table-column prop="academy" label="学院" width="140"></el-table-column>
        <el-table-column prop="className" label="班级" width="140"></el-table-column>
        <el-table-column label="操作" width="100">
          <template #default="{ row }">
            <el-button type="danger" @click="removeStudent">移除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-button v-if="selete_student == null" style="width: 100px;margin-left: 100px;margin-top: 20px;" type="primary" @click="fetchStudents();student_display=true">选择负责人</el-button>
      <div style="display: flex;margin-left: 400px;margin-top: 20px;">
        <el-button  type="success" @click="handleAddProject(AddProject)">确认添加</el-button>
        <el-button @click="handleCancelAddProject">取消</el-button>
      </div>

    </div>


  </el-dialog>


<!--  分页查询教师信息和条件查询 但是条件只有userName和professional,同样使用filters_student-->
  <el-dialog v-model="teacher_display" title="查询教师信息" width="70%" style="height: 550px;">
    <el-form :inline="true" :model="filters_teacher" style="margin-left: 60px;">
      <el-form-item label="姓名">
        <el-input v-model="filters_teacher.userName" style="width: 140px;"></el-input>
      </el-form-item>
      <el-form-item label="专业">
        <el-input v-model="filters_teacher.professional" style="width: 140px;"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="fetchTeachers">查询</el-button>
        <!--        重置-->
        <el-button type="success" @click="resetFilters_teacher">重置</el-button>
      </el-form-item>
    </el-form>
    <el-table :data="teacher_data" style="width: 100%">
      <el-table-column label="头像" width="80">
        <template #default="{ row }">
          <el-avatar :size="40" :src="row.avatar || 'https://via.placeholder.com/80'"></el-avatar>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="姓名" width="100"></el-table-column>
      <el-table-column prop="age" label=" 年龄" width="150"></el-table-column>
      <el-table-column prop="major" label="研究方向"></el-table-column>
      <el-table-column prop="professional" label="职称"></el-table-column>
      <el-table-column prop="phone" label="电话"></el-table-column>
      <el-table-column label="操作" width="100">
        <template #default="{ row }">
          <el-button type="success" @click="handleSelectTeacher(row)">添加</el-button>
        </template>
      </el-table-column>

    </el-table>
    <!--      分页参数-->
    <el-pagination
        background
        layout="total, prev, pager, next"
        :current-page="filters_teacher.pageNum"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="filters_teacher.pageSize"
        :total="teacher_total"
        @current-change=" handleTeacherPageChange"
        style="margin-top: 20px;margin-left:300px;"
    />

    </el-dialog>



  <!-- 分页查询学生信息和条件查询 -->
  <el-dialog v-model="student_display" title="查询学生信息" width="70%" style="height: 550px;">
    <el-form :inline="true" :model="filters_student" style="margin-left: 60px;">
      <el-form-item label="姓名">
        <el-input v-model="filters_student.userName" style="width: 140px;"></el-input>
      </el-form-item>
      <el-form-item label="班级">
        <el-input v-model="filters_student.className" style="width: 140px;"></el-input>
      </el-form-item>
      <el-form-item label="学院">
        <el-input v-model="filters_student.academy" style="width: 150px;"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="fetchStudents">查询</el-button>
        <!--        重置-->
        <el-button type="success" @click=" resetFilters_student">重置</el-button>
      </el-form-item>
    </el-form>
    <el-table :data="student_data" style="width: 100%">
      <el-table-column label="头像" width="80">
        <template #default="{ row }">
          <el-avatar :size="40" :src="row.avatar || 'https://via.placeholder.com/80'"></el-avatar>
        </template>
      </el-table-column>
      <el-table-column prop="userName" label="姓名" width="100"></el-table-column>
      <el-table-column prop="email" label="邮箱" width="150"></el-table-column>
      <el-table-column prop="phone" label="电话"></el-table-column>
      <el-table-column prop="academy" label="学院"></el-table-column>
      <el-table-column prop="className" label="班级"></el-table-column>
      <el-table-column label="操作" width="100">
        <template #default="{ row }">
          <el-button type="success" @click="handleSelectStudent(row)">添加</el-button>
        </template>
      </el-table-column>


    </el-table>
    <!--      分页参数-->
    <el-pagination
        background
        layout="total, prev, pager, next"
        :current-page="filters_student.pageNum"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="filters_student.pageSize"
        :total=" student_total"
        @current-change="handleStudentPageChange"
        style="margin-top: 20px;margin-left:300px;"
    />



  </el-dialog>
</template>


<style scoped>
.el-card {
  border: 1px solid #ebeef5;
  border-radius: 8px;
}
.el-row {
  margin-top: 20px;
}
.filter-form {
  display: flex;
  flex-wrap: nowrap; /* 强制一行显示 */
  align-items: center;
  gap: 10px; /* 控制表单项间距 */
  margin-top: 20px;
  margin-right: -20px;
}

.el-form-item {
  flex-shrink: 0; /* 禁止表单项缩小 */
}

.el-form-item:last-child {
  margin-left: auto; /* 将按钮组推到最右侧 */
}
.project-description {
  font-size: 14px;
  color: #555;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2; /* 限制为2行，超出部分会显示省略号 */
  overflow: hidden;
  text-overflow: ellipsis;
  width: 100%;
}

</style>
